//index.js
//获取应用实例
const WXAPI = require('apifm-wxapi')
var app = getApp()

Page({
  data: {
    goodsList: [],
    allGoodsPrice: 0,
    goodsJsonStr: "",
    orderType: "" //订单类型，购物车下单或立即支付下单，默认是购物车
  },
  onShow: function () {
    var that = this;
    var shopList = [];
    //立即购买下单
    if ("buyNow" === that.data.orderType) {
      console.log('buyNow!!'+JSON.stringify( wx.getStorageSync('buyNowInfo')))
      var buyNowInfoMem = wx.getStorageSync('buyNowInfo');
      that.data.kjId = buyNowInfoMem.kjId;
      if (buyNowInfoMem && buyNowInfoMem.shopList) {
        shopList = buyNowInfoMem.shopList
      }
    } else {
      //购物车下单
      var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
      that.data.kjId = shopCarInfoMem.kjId;
      if (shopCarInfoMem && shopCarInfoMem.shopList) {
        // shopList = shopCarInfoMem.shopList
        shopList = shopCarInfoMem.shopList.filter(entity => {
          return entity.active;
        });
      }
    }
    var amount = 0;
    for (var i=0;i<shopList.length;i++){ 
      amount+= shopList[i].price*shopList[i].number;
    }
    that.setData({
      allGoodsPrice : amount,
      goodsList: shopList
    })
    that.initShippingAddress();
  },

  

  onLoad: function (e) {
    var that = this;
    //显示收货地址标识
    that.setData({
      isNeedLogistics: 1,
      orderType: e.orderType
    });
  },

  // 创建支付订单(暂时只支持单个购买)
  async createOrder(e) {
    for(var i = 0;i<this.data.goodsList.length;i++){
      var data = this.data.goodsList[i];
      console.log("创建订单:"+JSON.stringify(data))
      //如果没有地址提示用户新建地址
      if(this.data.curAddressData == null){
        wx.showModal({
          title: '提示',
          content: "请选择收货地址",
          showCancel: false
        })
        return
      }
      var postData = {
        shelfId: data.goodsId,
        userId: wx.getStorageSync('userid'),
        userOrderNumber: data.number,
        userOrderPrice: data.price,
        userAddressId: this.data.curAddressData.id
      };
      console.log("创建订单信息："+JSON.stringify(postData))
      const res = await WXAPI.userOrderPlace(postData);
      console.log("创建订单结果："+JSON.stringify(res))
      //下单成功，开始付款
      if(res.code == 20000){
        wx.showLoading({
          title: '付款中...',
        })
        //付款
        var payData = {
          userOrderId : res.data
        }
        const payRes = await WXAPI.userPayOrder(payData);
        console.log("支付结果："+JSON.stringify(payRes))
        wx.hideLoading();
        if(payRes.code == 20000){
          // 支付成功跳转到订单界面
          wx.redirectTo({
            url: "/pages/ucenter/order-list/index"
          });
        }else{
          wx.showModal({
            title: '提示',
            content: payRes.msg,
            showCancel: false
          })
        }
      }
    }
  },

  actioncnt:function(e){  
    var that = this;
    wx.showActionSheet({  
        itemList: ['余额支付','支付宝支付', '微信支付', '银行卡支付','货到付款'],  
        success: function(res) {
          console.log(res.tapIndex)
          if(res.tapIndex != 0){
            return;
          }
          that.createOrder(e);
        },  
        fail: function(res) {  
            console.log(res.errMsg)  
        }  
    })  
  },

  addAddress : function () {
    wx.navigateTo({
      url:"/pages/address-add/index"
    })
  },

  async initShippingAddress () {
    var that = this;
    const res = await WXAPI.initShippingAddress({
      userId: wx.getStorageSync('userid')
    });
    console.log("获取收货地址成功"+JSON.stringify(res.data))
    if (res.code === 20000) {
      for(var index = 0 ;index < res.data.length;index++){
        if(res.data[index].isDefault ==1){
          that.setData({
            curAddressData: res.data[index]
          });
        }
      }
      
    } else {
      that.setData({
        curAddressData: null
      });
    }
  },

  selectAddress : function(){
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  }

  
})
